package com.neusoft.satoken.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.stp.StpUtil;
import com.neusoft.satoken.config.SaOauth2AppInfo;
import com.neusoft.satoken.util.SaOath2UtilImpl;
import com.neusoft.satoken.util.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;


@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    SaOauth2AppInfo saOauth2AppInfo;

    @Autowired
    SaOath2UtilImpl saOath2Util;

    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @RequestMapping("doLogin")
    public AjaxJson doLogin(String username, String password) throws UnsupportedEncodingException {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        if("zhang".equals(username) && "123456".equals(password)) {
            StpUtil.login(10001);
//            HashMap<String, Object> map = new HashMap<>();
//            map.put("access_token",StpUtil.getTokenValue());

//            String clientId = saOauth2AppInfo.getClientId();
//            RequestAuthModel authModel = new RequestAuthModel()
//                    .setClientId(saOauth2AppInfo.getClientId())			// 应用id
//                    .setScope(saOauth2AppInfo.getScope())				// 授权类型
//                    .setLoginId(StpUtil.getLoginIdAsLong())					// 当前登录账号id
//                    .setRedirectUri(URLDecoder.decode(saOauth2AppInfo.getRedirectUri(), "utf-8"))	// 重定向地址
//                    .checkModel();
//            AccessTokenModel accessTokenModel = SaOAuth2Util.generateAccessToken(authModel, true);
//            map.putAll(accessTokenModel.toLineMap());
            Map<String, Object> accessTokenAndRefreshToken = saOath2Util.createAccessTokenAndRefreshToken();
            return AjaxJson.getSuccess("success",accessTokenAndRefreshToken);
        }
        return AjaxJson.getError();
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    @GetMapping("/testLogin")
    public AjaxJson testLogin(){
        SaRequest request = SaHolder.getRequest();

        System.out.println("Authorization:" + request.getHeader("Authorization"));
        System.out.println(request);
        ArrayList<String> arr = new ArrayList<>();
        arr.add("aaaa");
        arr.add("bbbb");
//        String token = JwtToken.generateTokenRSA("zxcv", 10);
//        arr.add(token);
//        Claims claims = JwtToken.parseTokenRSA(token);
//        System.out.println(claims.toString());

        return AjaxJson.getSuccessData(arr);
    }

}
